import React, { useEffect, useState } from 'react'
import { Button, Form, Input, Table, Popconfirm, Modal, InputNumber, Select, DatePicker } from 'antd'
import './user.css'
import { getUser, addUser, editUser, delUser } from '../../api'
import dayjs from 'dayjs'
const User = () => {
  const [listData, setListData] = useState({ name: '' })

  const [tableData, setTabData] = useState([])

  //新增0 编辑1
  const [modelType, setModelType] = useState(0)

  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()

  const handleClick = (type, rowData) => {
    setIsModalOpen(!isModalOpen)
    if (type === 'add') {
      setModelType(0)
    } else {
      setModelType(1)
      const cloneData = JSON.parse(JSON.stringify(rowData))
      console.log(cloneData)
      cloneData.birth = dayjs(cloneData.birth)
      //表单数据回填
      console.log(form)
      form.setFieldsValue(cloneData)
    }
  }

  const handleDelete = ({ id }) => {
    delUser({ id }).then(res => {
      getTableData()
    })
  }
  const handleFinish = e => {
    setListData({
      name: e.keyword,
    })
    console.log(e)
  }
  useEffect(() => {
    getTableData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [listData])

  //弹窗确定
  const handleOk = () => {
    //表单校验
    form
      .validateFields()
      .then(val => {
        //新增
        console.log(val)
        val.birth = dayjs(val.birth).format('YYYY-MM-DD')
        console.log(val)
        //掉后端接口
        if (modelType) {
          //编辑
          editUser(val).then(res => {
            handleCancel()
            getTableData()
          })
        } else {
          //新增
          addUser(val).then(res => {
            handleCancel()
            getTableData()
          })
        }
      })
      .catch(err => {
        console.log(err)
      })
  }
  //弹窗取消
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  const getTableData = () => {
    getUser(listData).then(({ data }) => {
      setTabData(data.list)
    })
  }
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      render: val => {
        return val ? '女' : '男'
      },
    },
    {
      title: '出生日期',
      dataIndex: 'birth',
    },
    {
      title: '地址',
      dataIndex: 'addr',
    },
    {
      title: '操作',
      render: rowData => {
        return (
          <div className="flex-box1">
            <Button style={{ marginRight: '5px' }} onClick={() => handleClick('edit', rowData)}>
              编辑
            </Button>

            <Popconfirm
              title="提示"
              description="此操作会删除，是否继续？"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(rowData)}
            >
              <Button type="primary" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        )
      },
    },
  ]
  useEffect(() => {
    //调用接口 请求用户数据
    getTableData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  return (
    <div className="user">
      <div className="flex-box">
        <Button type="primary" onClick={() => handleClick('add')}>
          +新增
        </Button>
        <Form layout="inline" onFinish={handleFinish}>
          <Form.Item name="keyword">
            <Input placeholder="请输入用户名"></Input>
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <Table columns={columns} dataSource={tableData} rowKey={'id'} />
      <Modal
        open={isModalOpen}
        title={modelType ? '编辑用户' : '新增用户'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{
            span: 6,
          }}
          wrapperCol={{ span: 18 }}
          labelAlign="left"
        >
          {modelType === 1 && <Form.Item name="id" hidden></Form.Item>}
          <Form.Item
            label="姓名"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入姓名',
              },
            ]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item
            label="年龄"
            name="age"
            rules={[
              {
                required: true,
                message: '请输入年龄',
              },
              {
                type: 'number',
                message: '请输入数字',
              },
            ]}
          >
            <InputNumber placeholder="请输入年龄" />
          </Form.Item>
          <Form.Item
            label="性别"
            name="sex"
            rules={[
              {
                required: true,
                message: '请选择性别',
              },
            ]}
          >
            <Select
              placeholder="请选择性别"
              options={[
                { value: 0, label: '男' },
                { value: 1, label: '女' },
              ]}
            ></Select>
          </Form.Item>
          <Form.Item
            label="出生日期"
            name="birth"
            rules={[
              {
                required: true,
                message: '请选择出生日期',
              },
            ]}
          >
            <DatePicker placeholder="请选择" format="YYYY/MM/DD" />
          </Form.Item>
          <Form.Item
            label="地址"
            name="addr"
            rules={[
              {
                required: true,
                message: '请输入地址',
              },
            ]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default User
